package utils

import (
	"sync"
)

type EventType string

type Event struct {
	Type EventType
	Data interface{}
}

type EventHandler func(event Event)

type EventBus struct {
	handlers map[EventType][]EventHandler
	mutex    sync.RWMutex
}

func NewEventBus() *EventBus {
	return &EventBus{
		handlers: make(map[EventType][]EventHandler),
	}
}

func (eb *EventBus) Subscribe(eventType EventType, handler EventHandler) {
	eb.mutex.Lock()
	defer eb.mutex.Unlock()
	eb.handlers[eventType] = append(eb.handlers[eventType], handler)
}

func (eb *EventBus) Publish(event Event) {
	eb.mutex.RLock()
	defer eb.mutex.RUnlock()
	if handlers, ok := eb.handlers[event.Type]; ok {
		for _, handler := range handlers {
			go handler(event)
		}
	}
}
